package com.qiye.livevideo.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor.HSSFColorPredefined;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created on 2019/4/19.
 *
 * @author meishijun
 */
public class ExcelUtils {
    static Pattern p = Pattern.compile("^\\d+?$");
    private static final  String COLOR = "red";
    private static final  String AGENT = "firefox";
    private static final  String USER_AGENT = "USER-AGENT";

    public ExcelUtils() {
    }

    public static <T> void exportExcel(String title, Map<String, String> headers, List<T> dataset, OutputStream out) {
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            if (MyStringUtils.isEmpty(title)) {
                title = "data";
            }

            HSSFSheet sheet = workbook.createSheet(title);
            sheet.setDefaultColumnWidth(15);
            HSSFRow row = sheet.createRow(0);
            int j = 0;
            Iterator var8 = headers.entrySet().iterator();

            while(var8.hasNext()) {
                Entry<String, String> header = (Entry)var8.next();
                HSSFCell cell = row.createCell(j++);
                HSSFRichTextString text = new HSSFRichTextString((String)header.getValue());
                cell.setCellValue(text);
            }

            Font font = workbook.createFont();
            font.setColor(HSSFColorPredefined.RED.getIndex());
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFont(font);
            Iterator<T> it = dataset.iterator();
            int index = 0;

            while(true) {
                while(it.hasNext()) {
                    ++index;
                    row = sheet.createRow(index);
                    T t = it.next();
                    if (t instanceof Map) {
                        Map map = (Map)t;
                        int i = 0;
                        Object color = map.get("_color");

                        Object value;
                        HSSFCell cell;
                        for(Iterator var29 = headers.entrySet().iterator(); var29.hasNext(); judgeType(cell, value)) {
                            Entry<String, String> header = (Entry)var29.next();
                            cell = row.createCell(i++);
                            if (color != null && COLOR.equals(color)) {
                                cell.setCellStyle(cellStyle);
                            }

                            value = map.get(header.getKey());
                            Object o = map.get((String)header.getKey() + "_color");
                            if (o != null && !(Boolean)o) {
                                cell.setCellStyle(cellStyle);
                            }
                        }
                    } else {
                        int i = 0;
                        Iterator var14 = headers.entrySet().iterator();

                        while(var14.hasNext()) {
                            Entry<String, String> header = (Entry)var14.next();
                            HSSFCell cell = row.createCell(i++);
                            String[] keys = ((String)header.getKey()).split("\\.");
                            Object value = getDataValue(keys, t, 0);
                            judgeType(cell, value);
                        }
                    }
                }

                workbook.write(out);
                return;
            }
        } catch (Exception var21) {
            throw new RuntimeException(var21);
        }
    }

    public static Object getDataValue(String[] keys, Object t, int index) {
        try {
            Method method = t.getClass().getMethod("get" + toUpperCaseFirstOne(keys[index]));
            Object value = method.invoke(t);
            if (value == null) {
                return null;
            } else if (keys.length - 1 == index) {
                return value instanceof Date ? DateUtils.formatDateTime((Date)value) : value;
            } else {
                ++index;
                return getDataValue(keys, value, index);
            }
        } catch (Exception var5) {
            throw new RuntimeException("导出异常", var5);
        }
    }

    public static String toUpperCaseFirstOne(String s) {
        return Character.isUpperCase(s.charAt(0)) ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }

    private static void judgeType(HSSFCell cell, Object value) {
        if (value != null) {
            if (value instanceof String) {
                Matcher matcher = p.matcher(value.toString());
                if (matcher.matches()) {
                    cell.setCellValue(Double.parseDouble(value.toString()));
                } else {
                    cell.setCellValue(value.toString());
                }
            } else if (!(value instanceof Integer) && !(value instanceof Long) && !(value instanceof Float) && !(value instanceof Double)) {
                cell.setCellValue(value.toString());
            } else {
                cell.setCellValue(Double.parseDouble(value.toString()));
            }

        }
    }

    public static void exportExcel(String title, Map<String, String> header, List list, HttpServletResponse response, HttpServletRequest request) {
        try {
            String fileName = title + DateUtils.formatDateByPattern(new Date(), "yyyyMMddHHmmss") + ".xls";
            String agent = request.getHeader(USER_AGENT);
            if (agent != null && agent.toLowerCase().indexOf(AGENT) > 0) {
                fileName = "=?UTF-8?B?" + new String(Base64.encodeBase64(fileName.getBytes("UTF-8"))) + "?=";
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("content-disposition", "attachment;filename=" + fileName);
            exportExcel(title, header, list, response.getOutputStream());
        } catch (IOException var7) {
            throw new RuntimeException(var7);
        }
    }



    /**
     * 下载模板
     * @param response
     * @param templateFileName
     * @param request
     * @throws Exception
     */
    public static void download(HttpServletResponse response, String templateFileName, HttpServletRequest request)
            throws Exception {

        // 定义EXCEL文档
        Workbook importExcelBook = null;
        InputStream is = null;
        // 获取指定地址下的EXELE文档
        ClassPathResource classPathResource = new ClassPathResource(templateFileName);
        try {
            is = classPathResource.getInputStream();
            importExcelBook = new HSSFWorkbook(is);
        } catch (Exception e) {
            is = classPathResource.getInputStream();
            importExcelBook = new XSSFWorkbook(is);
        }
        if (null != importExcelBook) {
            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + templateFileName);
            OutputStream os = null;

            try {
                os = response.getOutputStream();
                importExcelBook.write(os);
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (null != os) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }
}
